﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace Adams.Admin.DataAccess.Files
{
    public static class Create
    {
        public static Adams.Admin.DataTransfer.Files.Create.PageLoad PageLoad(int id)
        {
            var data = new Adams.Admin.DataTransfer.Files.Create.PageLoad();
            data.File = new Shared.Entities.Files.File();

            if (id > 0)
            {
                using (SqlDataReader dr = DB.RunDataReader(@"
SELECT FileID, Url FROM Files.Files WHERE FileID = @FileID
", CommandType.Text,
                DB.CreateParameter("@FileID", id, SqlDbType.Int)))
                {
                    dr.Read();
                    data.File.ID = dr["FileID"].DbInt();
                    data.File.Url = dr["Url"].DbString();
                }
            }

            return data;
        }

        public static void Save(DataTransfer.Files.Create.FormInput input)
        {
            DB.Run(@"
IF(@FileID > 0)
BEGIN
    UPDATE Files.Files SET
        Url = @Url, LastModified = GETUTCDATE()
    WHERE FileID = @FileID
END
ELSE
BEGIN
    INSERT INTO Files.Files (
        Url, LastModified)
    VALUES (
        @Url, GETUTCDATE()
        )
END
    ", CommandType.Text,
                    DB.CreateParameter("@FileID", input.ID.ToInt()),
                    DB.CreateParameter("@Url", input.Url.ToNString()));
        }

        public static Adams.Admin.DataTransfer.Files.Create.FileInfo GetFileInfo(string url, int FileId)
        {
            var data = new Adams.Admin.DataTransfer.Files.Create.FileInfo();

            using (SqlDataReader dr = DB.RunDataReader(@"
IF (@FileID > 0)
BEGIN
    SELECT Url
    FROM Files.Files
    WHERE FileID = @FileID
END

SELECT COUNT(*) AS Count
FROM Files.Files
WHERE Url = @Url
", CommandType.Text,
                DB.CreateParameter("@FileID", FileId),
                DB.CreateParameter("@Url", url)))
            {
                if (FileId > 0)
                {
                    dr.Read();
                    data.Url = dr["Url"].DbString();
                    dr.NextResult();
                }
                dr.Read();
                data.Exists = dr["Count"].DbInt() > 0;
            }

            return data;
        }
    }
}
